<?php

/**
 * This is the model class for table "{{product}}".
 *
 * The followings are the available columns in table '{{product}}':
 * @property integer $id
 * @property integer $categoryID
 * @property string $name
 * @property string $description
 * @property integer $sort
 * @property integer $enabled
 * @property integer $createddate
 * @property integer $modifieddate
 */
class Product extends CActiveRecord
{
  public $image;
  public $thumbnails = array(
    array('70','60'),
    array('160', '125'),
    array('250', '240'),
    array('520', '400')
  );
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Product the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{product}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('categoryID, name, description, sort', 'required'),
			array('categoryID, sort, enabled, createddate, modifieddate', 'numerical', 'integerOnly'=>true),
			array('name', 'length', 'max'=>255),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, categoryID, name, description, sort, enabled, createddate, modifieddate', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'categoryID' => 'Loại',
			'name' => 'Tên sản phẩm',
			'description' => 'Mô tả',
			'sort' => 'Thứ tự',
			'enabled' => 'Hiển thị',
			'createddate' => 'Ngày tạo',
			'modifieddate' => 'Ngày cập nhật',
		);
	}

 protected function beforeSave() {
    if($this->isNewRecord) {
      $this->createddate = time();
    }
    $this->modifieddate = time();
    return parent::beforeSave();
  }
	
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('categoryID',$this->categoryID);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('sort',$this->sort);
		$criteria->compare('enabled',$this->enabled);
		$criteria->compare('createddate',$this->createddate);
		$criteria->compare('modifieddate',$this->modifieddate);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
 public function getProducts($catID = '',$except = '')
  {
    if ($catID == '') { //get all products
      $products = Yii::app()->db->createCommand()
        ->select('t.id, t.name, t.description, t.sort')
        ->from('tbl_product as t')     
        ->where('t.enabled = 1')
        ->order('t.createddate DESC')
        ->queryAll();
    }
    else { //get products follow catID
      $products = Yii::app()->db->createCommand()
        ->select('t.id, t.name, t.description, t.sort, cat.name' )
        ->from('tbl_product as t')
        ->join('tbl_category as cat', 'cat.id = t.categoryID')
        ->where('t.enabled = 1 AND cat.enabled = 1 AND (md5(cat.parentID) = "'.$catID.'" OR md5(t.categoryID) = "' . $catID . '")')
        ->order('t.createddate DESC')
        ->queryAll();   

       if ($except != '') {
        $products = Yii::app()->db->createCommand()
          ->select('t.id, t.name, t.description, t.sort, cat.name')
          ->from('tbl_product as t')
          ->join('tbl_category as cat', 'cat.id = t.categoryID')
          ->where('t.enabled = 1 AND cat.enabled = 1 AND t.id<>' . $except . ' AND md5(t.categoryID) = "' . $catID . '"')
          ->order('t.createddate DESC')
          ->queryAll();
      }
    }
    return $products;
  }
  
 public function getProductFile($productID, $w, $h)
  {
    $product_files = FileProduct::model()->findByAttributes(array('productID' =>$productID));
    $image = 'no_image.jpg';
    if (!empty($product_files)) {
      $file = $product_files->file;
      if (!empty($file) && file_exists(Yii::app()->basePath . "/../upload/product/thumbs_$w"."x"."$h/" . $file->filesaved)) {
        $image = $file->filesaved;
      }
    }
    return $image;
  }
  
 public function getProductFiles($productID, $except = '')
  {
    $image         = array();
    $product_files  = FileProduct::model()->findAllByAttributes(array(
      'productID' => $productID
    ));
    if (!empty($product_files)) {
      foreach ($product_files as $product_file) {
        $i = File::model()->findByAttributes(array(
          'id' => $product_file->fileID,
          'filetype' => 'image'
        ));
        if (!empty($i) && file_exists(Yii::app()->basePath . '/../upload/product/post-images/' . $i->filesaved)) {
          if ($except != '' && $except == $i->filesaved)
            continue;
          $image[$i->id] = array(
            'id' => $i->id,
            'name' => $i->filename,
            'save' => $i->filesaved
          );
        }
      }
    }
    return $image;
  }
}